﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace IDEAMS.common.validation
{
    public class IpAddressRule : ValidationRule
    {
        public string errString { get; set; }

        public bool isNullable { get; set; }

        public IpAddressRule()
        {
            isNullable = true;
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            bool rn = false;

            try
            {
                if (isNullable && string.IsNullOrEmpty((string)value))
                {
                    return new ValidationResult(false, $"不能为空");
                }

                IPAddress _ip;
                rn = IPAddress.TryParse((string)value, out _ip);
                if (!rn)
                {
                    return new ValidationResult(false, errString);
                }
            }
            catch (Exception e)
            {
                return new ValidationResult(false, $"输入字符不合法或者{e.Message}");
            }

            if (rn == false)
            {
                return new ValidationResult(false, errString);
            }

            return ValidationResult.ValidResult;
        }
    }
}
